package com.woniuxy.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.common.DTO.ResponseResult;
import com.woniuxy.common.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author: linKe
 * @Date: 2022/2/10 14:56
 * @FileName: GlobalFilter
 * @version: 1.0
 * @Description: 生成token 测试
 */
@Slf4j
@Component
public class LoginTokenFilter implements GlobalFilter, Ordered {

    /**
     * GlobalFilter 拦截的核心方法
     * Mono : Gateway底层是Netty，NIO   不是以前的ServletApi
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("进入loginfilter");
        ServerHttpRequest request = exchange.getRequest();
        //某些路径可以直接放行
        if (request.getURI().getPath().contains("login")) {
            log.info("请求登录页面，直接放行");
            return chain.filter(exchange);
        }
        //token验证
        log.info("token验证");
        String token = request.getHeaders().getFirst("token");
        if(!StringUtils.isEmpty(token) && JwtUtil.verify(token)){
            log.info("token有效，放行");
            return chain.filter(exchange);
        }
        log.info("token无效，拦截用户请求");
        return exchange.getResponse().writeWith(Mono.just(getDataBuffer(exchange)));
    }

    /**
     * 获取dataBuffer对象
     * @param exchange
     * @return
     */
    DataBuffer getDataBuffer(ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        ResponseResult<String> result = new ResponseResult<>(401, "auation", "先登录");
        //定义字节数组
        byte[] data=null;
        //序列化JSON
        try {
            data=new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            log.info("json格式化异常：{}",e);
            /// e.printStackTrace();
        }
        // 封装成Data缓冲
        DataBuffer dataBuffer=response.bufferFactory().wrap(data);
        //设置JSON响应头，否则中文乱码
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");
        return dataBuffer;
    }




    @Override
    public int getOrder() {
        return 0;
    }
}
